package com.study.spark.scala.rdd

import org.apache.spark.{SparkConf, SparkContext}

/**
  * 排序示例-在对象中排序
  * @author stephen
  * @create 2019-03-15 11:48
  * @since 1.0.0
  */
object OrderDemo_Object {

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
      .setAppName("Order Object Demo")
      .setMaster("local[*]")
    val sc = new SparkContext(conf)

    val persons = List("zhangsan 25 90","lisi 20 98","wangwu 30 80","zhaoliu 25 98")
    val rdd = sc.parallelize(persons)
    val result = rdd.map(line => {
      val splits = line.split(" ")
      new User(splits(0), splits(1).toInt, splits(2).toInt)
    }).sortBy(u => u)  // 排序
      .collect()

    println(result.toBuffer)

  }
}

class User(val name: String, val age: Int, val score: Int) extends Ordered[User] with Serializable {

  override def compare(that: User): Int = {
    // 先按照分数降序排，分数相同按照年龄升序排
    if(this.score==that.score){
      this.age-that.age
    }else{
      -(this.score-that.score)
    }
  }

  override def toString: String = {
    s"name: $name, age: $age, score: $score"
  }
}
